import React from "react";
import {Space, Tag} from "antd";
import styles from './index.less'
import {useSelector, useDispatch} from 'react-redux'
import {setTabList, setCurrentTabPath} from "../../store/reducers/tab";
import {useNavigate} from 'react-router-dom'

export default () => {
    const tabList = useSelector(state => state.tab.tabList)
    const currentTabPath = useSelector(state => state.tab.currentTabPath)

    const dispatch = useDispatch()
    const navigate = useNavigate()
    const handelClose = (data, index) => {
        let newPath;
        if (data.path === currentTabPath) {
            if (index === tabList.length - 1 && tabList.length > 1) newPath = tabList[tabList.length - 2].path
            if(index !== tabList.length - 1) newPath = tabList[index+1].path
        }
        dispatch(setTabList({data, type: 'close'}))
        !!newPath && dispatch(setCurrentTabPath(newPath))
    }
    const handelClick = (path) => {
        navigate(path)
        dispatch(setCurrentTabPath(path))
    }


    return (<Space wrap size={[0, 8]} className={styles['common-tag']}>
        {!!tabList.length && tabList.map((item, index) => {
            return (<Tag closeIcon={item.path !== '/home'} onClick={() => handelClick(item.path)}
                         onClose={() => handelClose(item, index)}
                         color={item.path === currentTabPath ? '#2db7f5' : ''}
                         key={item.path}>
                {item.label}
            </Tag>)
        })
        }

    </Space>)
}